package com.sishu.websocket4.service.impl;

//import com.sishu.websocket.Mapper.TransactionMapper;

import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sishu.websocket4.mapper.*;
import com.sishu.websocket4.pojo.*;
import com.sishu.websocket4.service.Userservice;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;

@Service
public class UserServiceimpl implements Userservice {

    @Resource
    private UserMapper userMapper;

    @Resource
    private GroupsMapper groupsMapper;

    @Resource
    private AssetsMapper assetsMapper;

    @Resource
    private MapSitesMapper mapSitesMapper;

    @Resource
    private buyRecordMapper buyRecordMapper;

    @Resource
    private TransactionRecordMapper transactionRecordMapper;



    @Override
    public User getUserByName(String username) {
        return userMapper.selectOne(
                new QueryWrapper<User>().eq("user_name", username));
    }

    @Override
    public User getUserByUserId(String userId) {
        return userMapper.selectOne(new QueryWrapper<User>().eq("user_id", userId));
    }

    //注册
    public SaResult register(String username, String password, String uid, String type) {
        // 检查用户ID是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid);
        User existingUser = userMapper.selectOne(queryWrapper);

        if (existingUser != null) {
            // 用户ID已存在，可以选择更新或返回错误信息
            return SaResult.error("用户ID已存在，请选择其他ID");
        }

        User user = new User();
        user.setUserId(uid);
        user.setUserName(username);
//        user.setUserPassword(password);
        user.setUserType(type);
        userMapper.insert(user);
        return SaResult.ok("插入users数据库成功");
    }

    //新增组
    @Override
    public SaResult insertgroups(List<User> Users, String sessionid) {

        //得到一个user组
        //遍历groupid将每一个user插入到数据库中
        Users.forEach(user -> {
            Groups Groups = new Groups();
            Groups.setGroupMember(user.getUserId());
            Groups.setGroupId(sessionid);
            groupsMapper.insertgroups(Groups);
        });
        return SaResult.ok("插入usersgroup数据库成功").setData(sessionid);
    }

    //新增资产
    public void insetAssets(String uid, String username, String password, String point) {
    }

    //新增用户
    @Override
    public void insertusers(User user) {

        userMapper.insertusers(user);
    }

    @Override
    public SaResult insetAssets(String groupId, String userId) {
        Assets assets = new Assets();
        assets.setGroupId(groupId);
        assets.setUserId(userId);
        assetsMapper.insert(assets);
        return SaResult.ok("插入assets数据库成功");
    }

    @Override
    public String selectusername(String userId) {
        System.out.println("userId: " + userId);
        User user = userMapper.selectbyUserId(userId);
        System.out.println(user);
        if (user != null) {
            return user.getUserName();
        } else {
            return "null"; // 或者返回一个默认值，比如 "Unknown"
        }
    }

    @Override
    // 判断用户是否存在
    public boolean isuserExists(String userId) {
        User user = userMapper.selectbyUserId(userId);
        if (user == null || user.getUserId().isEmpty()) {
            return false;
        } else return true;
    }

    @Override
    //购买地盘
    public SaResult buygroud(String userId, String siteid,String groupid) {
        //资产表的用户数据
        Assets assets = assetsMapper.selectbyUserId(userId, groupid);
        //买地表的数据
        MapSites sites = mapSitesMapper.selectbysiteid(siteid);
        System.out.println(sites);

        //没买过地
        if (sites.getStatus() == 0) {
            //创建一个buyrecord对象
            buyRecord buyRecord = new buyRecord();
            buyRecord.setSiteId(sites.getSiteId());
            buyRecord.setUserId(assets.getUserId());
            buyRecord.setGroupId(assets.getGroupId());
            buyRecordMapper.insert(buyRecord);
            //设置set==1
            mapSitesMapper.updatestatus(siteid);

            // 如果资产表流动资产大于地盘价格
            if (assets.getFluidAssets() >= sites.getSitePrice()) {
                //1.更新资产表
                //减去后的流动资产
                int asset = assets.getFluidAssets() - sites.getSitePrice();

                //更新流动资产(              用户id,减去后的流动资产,地盘的价格)
                assetsMapper.updateassets(userId, asset, sites.getSitePrice());
                //更新地盘表,设置地盘的拥有者
                // mapSitesMapper.updatesites(sitename, assets.getGroupId());
                // 2.跟新地盘表

                 inserttranscationrecored(userId,"银行", sites.getSitePrice(), "购买地盘",
                         new Timestamp(System.currentTimeMillis()),sites.getSiteId(), assets.getGroupId(),userId);
                return SaResult.ok("购买成功," + sites.getSiteName() + "已经成功购入");
            } else return SaResult.error("用户流动资产不够,无法购买地盘");
        } else {
            //查询该地盘是否被购买
            List<buyRecord> buyRecord = buyRecordMapper.selectbysiteId(sites.getSiteId());
            System.out.println("循环前");
            System.out.println(buyRecord);
            // 检查同组内是否有已购买的地盘
            boolean flag = false;
            for (buyRecord record : buyRecord) {
                System.out.println("循环后");
                System.out.println(record.getGroupId());
//                System.out.println("record"+ record);
                // 同一组的就不能买
                if (record.getGroupId().equals(assets.getGroupId())) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return SaResult.error("同一组内地盘已经被购买");
            }
            //不同组的
            buyRecord buyRecord2 = new buyRecord();
            buyRecord2.setSiteId(sites.getSiteId());
            buyRecord2.setUserId(assets.getUserId());
            buyRecord2.setGroupId(assets.getGroupId());
            buyRecordMapper.insert(buyRecord2);

            // 如果资产表流动资产大于地盘价格
            if (assets.getFluidAssets() >= sites.getSitePrice()) {
                //1.更新资产表
                //减去后的流动资产
                int asset = assets.getFluidAssets() - sites.getSitePrice();

                //更新流动资产(用户id,减去后的流动资产,地盘的价格,地址信息)
                assetsMapper.updateassets(userId, asset, sites.getSitePrice());
                //更新地盘表,设置地盘的拥有者
               //mapSitesMapper.updatesites(sitename, assets.getGroupId());
                // 2.跟新地盘表
                inserttranscationrecored(userId,"银行", sites.getSitePrice(), "购买地盘",
                        new Timestamp(System.currentTimeMillis()),sites.getSiteId(), assets.getGroupId(),userId);
                return SaResult.ok("购买成功," +  sites.getSiteName() + "已经成功购入");
            } else return SaResult.error("用户流动资产不够,无法购买地盘");
        }




    }

    @Override
    //插入交易记录
    public void inserttranscationrecored(String playuserId, String geter_user_id, int amount, String transactionType,
                                         Timestamp transactionDate,String siteId,String groupId,String userId) {
        TransactionRecord transactionRecord = new TransactionRecord();
        transactionRecord.setPayerUserId(playuserId);
        transactionRecord.setGeterUserId(geter_user_id);
        transactionRecord.setAmount(amount);
        transactionRecord.setTransactionType(transactionType);
        transactionRecord.setTransactionDate(transactionDate);
        transactionRecord.setSiteId(siteId);
        transactionRecord.setGroupId(groupId);
        transactionRecord.setUserId(userId);
        transactionRecordMapper.insert(transactionRecord);
    }

    @Override
    //玩家a交易给玩家b
    public SaResult transaction(String payeruserId, String geteruserId, int amount,String groupid) {
        //付款的账号
        Assets payerAssets = assetsMapper.selectbyUserId(payeruserId,groupid);
        //收款的账号
//        Assets geterAssets = assetsMapper.selectbyUserId(geteruserId);

        if (payerAssets.getFluidAssets()<amount){
            return SaResult.error("用户流动资产不够,无法购买地盘");
        }
       else{
           //付款人资金减少,收款人资金增加(包括总资产和流动资产)
           assetsMapper.updateassetjian(payeruserId,amount,groupid);
           assetsMapper.updateassetjia(geteruserId,amount,groupid);
           inserttranscationrecored(payeruserId, geteruserId, amount, "转账",new Timestamp(System.currentTimeMillis()),
                   "", groupid,payeruserId);
        return  SaResult.ok("转账成功");
       }
    }

    @Override
    //卖地
    public SaResult saleground(String userId, String siteid,String groupid) {
          //查询用户所持有的地在不在
        buyRecord buyRecord = buyRecordMapper.selectbysiteIdanduserid(userId, siteid);
        //根据siteid查询数据
        MapSites MapSite = mapSitesMapper.selectbysiteid(siteid);
        System.out.println("buyRecord = " + buyRecord);
        if (buyRecord==null){
            return SaResult.error("用户没有此块地");
        }
            //删除地
        buyRecordMapper.deletegroud(userId,siteid);
        //流动资产++,固定资产--
        assetsMapper.updateassetjianfixed(userId,MapSite.getSitePrice(),groupid);

        inserttranscationrecored("银行", userId, MapSite.getSitePrice(),
                "卖地", new Timestamp(System.currentTimeMillis()), siteid, groupid,userId);
        return SaResult.ok(MapSite.getSiteName()+"卖地成功");
    }

    @Override
    public SaResult selectuser(User user) {
        //需要传过来的用户的id和数据库中的用户id相等

        //数据库中的所有user对象 select * from Users
        List<User> users = userMapper.selectAll();
        System.out.println("数据库users = " + users);
        boolean flag = false;//默认是数据库中是没有这个对象的
        for (User user1 : users) {//遍历数据库中的所有user对象
          if (user1.getUserId().equals(user.getUserId())){
              flag = true;//数据库中有这个对象
              return SaResult.ok("用户在数据库中已存在");
          }
        }
         if (!flag){//如果有这个对象，返回true，没有返回false
             return SaResult.error(user.getUserId()+"用户不存在,无法创建小组");
         }
        return SaResult.error("未知错误");
/*         当需要用到userId和userName来判断用户是否存在，可以使用以下代码：(
         把Usercontroller中的 if (selectuser.equals(SaResult.error(user.getUserId()+"用户不存在,无法创建小组")))
         改成if (selectuser.equals(SaResult.error(user.getUserId() + "用户不存在,或用户名不一致,无法创建小组")))
        */
//        数据库中的user对象
//        List<User> users = userMapper.selectAll();
//
//        // 创建一个包含所有数据库中 userId 和 userName 的映射
//        Map<String, String> userMap = users.stream()
//                .collect(Collectors.toMap(User::getUserId, User::getUserName));
//
//        // 检查用户是否存在且用户名一致
//        if (userMap.containsKey(user.getUserId()) && userMap.get(user.getUserId()).equals(user.getUserName())) {
//            return SaResult.ok("用户存在");
//        } else {
//            return SaResult.error(user.getUserId() + "用户不存在,或用户名不一致,无法创建小组");
//        }
    }

    @Override
    public SaResult answerjia(String userId, int amount,String groupid) {
        //总资产++,流动资产++
       assetsMapper.updateassetjia(userId,amount,groupid);
       inserttranscationrecored("银行", userId, amount, "答题得款",
               new Timestamp(System.currentTimeMillis()),"",groupid, userId);
        return SaResult.ok("答题得款成功");
    }

    @Override
    public SaResult answerkou(String userId, int amount,String groupid) {
        Assets assets = assetsMapper.selectbyUserId(userId,groupid);
        if (assets.getFluidAssets()<amount)
        {
            return SaResult.error("用户流动资产不够,无法扣款,需要您抵押地盘");
        }
        //总资产--,流动资产--
        assetsMapper.updateassetjian(userId,amount,groupid);
        inserttranscationrecored( userId,"银行", amount, "答题扣款",new Timestamp(System.currentTimeMillis()),
                "", groupid,userId);
        return SaResult.ok("答题扣款成功");
    }

    @Override
    public SaResult selcetgroupasset(String groupid) {
        List<Assets> selectbygroupid = assetsMapper.selectbygroupid(groupid);
        System.out.println("selectbygroupid = " + selectbygroupid);
        return SaResult.ok("数据查询成功").setData(selectbygroupid);
    }

    @Override
    public SaResult card(TransactionRecord record) {
        if (record.getAmount()>0){
            //总资产++,流动资产++
            assetsMapper.updateassetjia(record.getUserId(),record.getAmount(), record.getGroupId());
            inserttranscationrecored(
                    record.getPayerUserId(),record.getGeterUserId(), record.getAmount(), "抽卡",new Timestamp(System.currentTimeMillis()),
                    "", record.getGroupId(), record.getUserId()
            );
           return SaResult.ok("抽卡得款成功");
        }
        else {
            //当是负数时,取其绝对值
            int amount = Math.abs(record.getAmount());
            //总资产--,流动资产--
            assetsMapper.updateassetjian(record.getUserId(),amount, record.getGroupId());
            //交换交易双方
            inserttranscationrecored(
                    record.getGeterUserId() , record.getPayerUserId(), amount, "抽卡",new Timestamp(System.currentTimeMillis()),
                    "", record.getGroupId(), record.getUserId()
            );
            return SaResult.ok("抽卡扣款成功");
        }
    }

    public String insertOrUpdate(websocketuser user) {
//        userMapper.insertOrUpdate(user);
//        userMapper.insert(user);
        return "数据库添加成功";
    }


}













//              //如果为null表示没有人购买过这块地
//        if (sites.getSiteBuygroupId()==null){
//
//            //如果资产表流动资产大于地盘价格
//            if (assets.getFluidAssets() >= sites.getSitePrice())
//            {
//                //1.更新资产表
//                //减去后的流动资产
//                int asset = assets.getFluidAssets()-sites.getSitePrice();
//                if(assets.getFixedSite()==null){
//                    fixedsite = sites.getSiteId();
//                }
//                else{
//                    fixedsite += ","+sites.getSiteId();
//                }
//                //更新流动资产(用户id,减去后的流动资产,地盘的价格,地址信息)
//                assetsMapper.updateassets(userId,asset,sites.getSitePrice(),fixedsite);
//                //更新地盘表,设置地盘的拥有者
//                mapSitesMapper.updatesites(sitename,assets.getGroupId());
//                // 2.跟新地盘表
//                return SaResult.ok("购买成功," + sitename + "已经成功购入");
//            }
//            else return SaResult.error("用户流动资产不够,无法购买地盘");
//        }
//        else
//        {
//            //如果插入的是同一组
//              if (assets.getGroupId().equals(sites.getSiteBuygroupId())){
//                       return SaResult.error("同一组内不能购买同一地盘");
//              }
//              //如果是不同组的话就可以买
//           else{
//                  //如果资产表流动资产大于地盘价格
//                  if (assets.getFluidAssets() >= sites.getSitePrice())
//                  {
//                      //1.更新资产表
//                      //减去后的流动资产
//                      int asset = assets.getFluidAssets()-sites.getSitePrice();
//                      if(assets.getFixedSite()==null){
//                          fixedsite = sites.getSiteId();
//                      }
//                      else{
//                          fixedsite += ","+sites.getSiteId();
//                      }
//                      //更新流动资产(用户id,减去后的流动资产,地盘的价格,地址信息)
//                      assetsMapper.updateassets(userId,asset,sites.getSitePrice(),fixedsite);
//                      //更新地盘表,设置地盘的拥有者
//                      mapSitesMapper.updatesites(sitename,assets.getGroupId());
//                      // 2.跟新地盘表
//                      return SaResult.ok("购买成功," + sitename + "已经成功购入");
//                  }
//                  else return SaResult.error("用户流动资产不够,无法购买地盘");
//              }
//           }
//      }







//    @Override
//    public User registeruser(String username, String password) {
//
//        User user = new User();
//        user.setUsername(username);
//        user.setPassword(password);
//        user.setPoint(10000);
//        userMapper.insertuser(user);
//        return user;
//    }
//
//    @Override
//    public String login(String username, String password) {
//        User user = userMapper.selectBynamepassword(username,password);
//        if (user == null) {
//           return "错误的用户名以及密码,请重新输入";
//        }
//        return "登录成功";
//    }
